package chatroomclient;

import chatroomsend.Send;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList; // 确保导入 java.util.List
import java.util.List; // 确保导入 java.util.List

public class FriendManagementFrame extends JFrame {
    private String myId;
    private String serverIP;
    private int serverPort;

    private JList<String> friendsList; // 修改为普通字符串列表
    private JList<String> friendRequestsList;
    private JList<String> allUsersList;


    public FriendManagementFrame(String myId, String serverIP, int serverPort) {
        this.myId = myId;
        this.serverIP = serverIP;
        this.serverPort = serverPort;

        setTitle("好友管理");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new GridLayout(1, 3));

        // 好友列表面板
        JPanel friendsPanel = createFriendsPanel();
        // 所有用户列表面板
        JPanel allUsersPanel = createAllUsersPanel();
        // 好友请求列表面板
        JPanel friendRequestsPanel = createFriendRequestsPanel();

        mainPanel.add(friendsPanel);
        mainPanel.add(allUsersPanel);
        mainPanel.add(friendRequestsPanel);

        add(mainPanel);
        setVisible(true);

        // 初始化 friendsList 和 friendRequestsList
        friendsList = (JList<String>) ((JScrollPane) friendsPanel.getComponent(0)).getViewport().getView();
        friendRequestsList = (JList<String>) ((JScrollPane) friendRequestsPanel.getComponent(0)).getViewport().getView();
        //加载好友请求
        loadFriendRequests(friendRequestsList);

        // 添加返回按钮
        JButton backButton = new JButton("返回聊天室");
        backButton.setBackground(Color.LIGHT_GRAY);
        backButton.addActionListener(e -> {
            dispose(); // 关闭当前窗口
            new ChatRoom(myId, serverIP, serverPort); // 打开聊天室
        });

        add(backButton, BorderLayout.SOUTH); // 放在底部
        revalidate();
        repaint();
    }

    private void deleteFriend(String userId, String friendId) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("delf" + userId + ":" + friendId);
        if ("deleted".equals(response)) {
            JOptionPane.showMessageDialog(this, "删除成功");
        } else {
            JOptionPane.showMessageDialog(this, "删除失败");
        }
    }

    private JPanel createFriendsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("我的好友"));

        friendsList = new JList<>(); // 修改为普通字符串列表
        friendsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 设置单选模式

        JButton deleteButton = new JButton("删除选中好友");
        JButton renameButton = new JButton("修改备注");

        // 加载好友列表
        loadFriends(friendsList);

        deleteButton.addActionListener(e -> {
            String selectedFriend = friendsList.getSelectedValue();
            if (selectedFriend != null) {
                // 解析 friendId 和 friendName
                String[] parts = selectedFriend.split(":");
                if (parts.length == 2) {
                    String friendId = parts[0].trim(); // 提取 friendId
                    deleteFriend(myId, friendId); // 仅传递 friendId
                    loadFriends(friendsList); // 刷新好友列表
                } else {
                    JOptionPane.showMessageDialog(this, "好友信息格式错误，请重试！");
                }
            }
        });

        renameButton.addActionListener(e -> {
            String selectedFriend = friendsList.getSelectedValue();
            if (selectedFriend != null) {
                // 解析 friendId 和 friendName
                String[] parts = selectedFriend.split(":");
                if (parts.length == 2) {
                    String friendId = parts[0].trim(); // 提取 friendId
                    String friendName = parts[1].trim(); // 提取 friendName

                    // 显示输入对话框，默认值为当前备注名
                    String newName = JOptionPane.showInputDialog(this, "请输入新备注名", friendName);
                    if (newName != null && !newName.isEmpty()) {
                        updateFriendName(myId, friendId, newName); // 仅传递 friendId
                        loadFriends(friendsList); // 刷新好友列表
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "好友信息格式错误，请重试！");
                }
            }
        });

        panel.add(new JScrollPane(friendsList), BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        buttonPanel.add(deleteButton);
        buttonPanel.add(renameButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }


    private void filterAllUsers(String keyword) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("searchu" + keyword); // 自定义命令
        String[] users = response.split(";");
        allUsersList.setListData(users);
    }

    private JPanel createAllUsersPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("所有用户"));

        allUsersList = new JList<>();
        JButton sendRequestButton = new JButton("发送好友申请");

        // 新增：搜索部分
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(15);
        JButton searchButton = new JButton("确认");
        JButton resetButton = new JButton("重置");

        // 设置 preferredSize 避免布局拉伸
        searchPanel.setPreferredSize(new Dimension(800, 100)); // 固定高度
        searchField.setMaximumSize(new Dimension(200, 100));   // 限制宽度
        searchButton.setMaximumSize(new Dimension(80, 100));
        resetButton.setMaximumSize(new Dimension(80, 100));

        searchButton.addActionListener(e -> {
            String keyword = searchField.getText().trim();
            filterAllUsers(keyword);
        });

        resetButton.addActionListener(e -> {
            searchField.setText("");
            loadAllUsers(allUsersList);
        });

        searchPanel.add(new JLabel("搜索:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        searchPanel.add(resetButton);

        sendRequestButton.addActionListener(e -> {
            String selectedUser = allUsersList.getSelectedValue();
            if (selectedUser != null) {
                addFriendRequest(selectedUser);
            }
        });

        // 用户列表区域：包裹在 JScrollPane 中并设置固定高度
        JScrollPane listScrollPane = new JScrollPane(allUsersList);
        listScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        listScrollPane.setPreferredSize(new Dimension(780, 400)); // 固定用户列表高度

        // 添加按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(sendRequestButton);

        // 布局组装
        panel.add(searchPanel, BorderLayout.NORTH);     // 上部搜索栏
        panel.add(listScrollPane, BorderLayout.CENTER);  // 中间带滚动条的列表
        panel.add(buttonPanel, BorderLayout.SOUTH);      // 下方按钮

        loadAllUsers(allUsersList);
        return panel;
    }


    private JPanel createFriendRequestsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("好友请求"));

        JList<String> friendRequestsList = new JList<>();
        JButton acceptRequestButton = new JButton("接受请求");

        acceptRequestButton.addActionListener(e -> {
            String selectedRequest = friendRequestsList.getSelectedValue();
            if (selectedRequest != null) {
                acceptFriendRequest(selectedRequest);
            }
        });

        panel.add(new JScrollPane(friendRequestsList), BorderLayout.CENTER);
        panel.add(acceptRequestButton, BorderLayout.SOUTH);

        return panel;
    }

    private void showFriendEditDialog(String friendId) {
        // 实现好友编辑对话框
        JOptionPane.showMessageDialog(this, "编辑好友: " + friendId);
    }

    private void loadFriends(JList<String> friendsList) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("listf" + myId);
        String[] friends = response.split(";");
        friendsList.setListData(friends);
    }

    private void loadAllUsers(JList<String> userList) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("allu");
        String[] users = response.split(";");

        // 过滤掉当前登录的用户
        List<String> filteredUsers = new ArrayList<>();
        for (String user : users) {
            if (!user.equals(myId)) { // 移除当前登录的用户
                filteredUsers.add(user);
            }
        }

        // 使用 toArray 方法将 List 转换为数组
        userList.setListData(filteredUsers.toArray(new String[0]));
    }

    private void loadFriendRequests(JList<String> requestsList) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("pendingf" + myId);
        String[] requests = response.split(";");
        requestsList.setListData(requests);
    }

    private void addFriendRequest(String friendId) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("addf" + myId + ":" + friendId);
        if ("added".equals(response)) {
            JOptionPane.showMessageDialog(this, "好友请求已发送！");
        } else {
            JOptionPane.showMessageDialog(this, "发送好友请求失败！");
        }
    }

    private void acceptFriendRequest(String friendId) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("accf" + myId + ":" + friendId);
        if ("accepted".equals(response)) {
            JOptionPane.showMessageDialog(this, "已接受好友请求！");
            // 刷新好友列表和请求列表
            loadFriends(friendsList);
            loadFriendRequests(friendRequestsList);
        } else {
            JOptionPane.showMessageDialog(this, "接受好友请求失败！");
        }
    }

    private void updateFriendName(String userId, String friendId, String newName) {
        Send sendClient = new Send();
        sendClient.connect(serverIP, serverPort, 1000);
        String response = sendClient.send("renamef" + userId + ":" + friendId + ":" + newName);
        if ("renamed".equals(response)) {
            JOptionPane.showMessageDialog(this, "备注名更新成功");
        } else {
            JOptionPane.showMessageDialog(this, "备注名更新失败");
        }
    }
}